<script>
import { isLoggedIn } from './utils/auth.js';

export default {
	onLaunch: function () {
		console.log('App Launch')
		// 初始化全局权限
		this.initAuth();
	},
	onShow: function () {
		console.log('App Show')
	},
	onHide: function () {
		console.log('App Hide')
	},
	methods: {
		// 初始化权限
		initAuth() {
			// 配置需要登录权限的页面路径
			const authRequiredPages = [
				/^pages\/points\/detail/,
				/^pages\/recycle\/order-detail/,
				/^pages\/address\/add/,
				/^pages\/address\/manage/,
				/^pages\/profile\/index/
			];

			// 监听页面跳转
			uni.addInterceptor('navigateTo', {
				invoke(params) {
					const url = params.url || '';

					// 检查是否需要登录权限
					const needAuth = authRequiredPages.some(regex => regex.test(url));

					if (needAuth && !isLoggedIn()) {
						// 跳转到登录页，并传递来源页面信息
						let fromPage = '';
						if (url.includes('/pages/profile/')) {
							fromPage = 'profile';
						} else if (url.includes('/pages/points/')) {
							fromPage = 'points';
						} else if (url.includes('/pages/recycle/')) {
							fromPage = 'recycle';
						} else if (url.includes('/pages/address/')) {
							fromPage = 'address';
						}

						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});

						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/login/index?from=' + fromPage
							});
						}, 1500);

						return false; // 拦截原来的跳转
					}

					return params;
				}
			});

			// 监听Tab切换
			uni.addInterceptor('switchTab', {
				invoke(params) {
					const url = params.url || '';

					// 检查是否需要登录权限
					if (url.includes('/pages/profile/index') && !isLoggedIn()) {
						// 跳转到登录页，标明是从个人中心页面来的
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});

						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/login/index?from=profile'
							});
						}, 1500);

						return false; // 拦截原来的跳转
					}

					return params;
				}
			});
		}
	}
}
</script>

<style>
/*每个页面公共css */
@import './static/fonts/iconfont.css';
</style>
